package my.edu.utils;

import my.edu.common.constant.OrderConstant;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderNoUtil {

    //ConcurrentHashMap线程安全的Map，和AtomicInteger线程安全的Integer
    //键：单据类型，值：「键：时间，值：当前分钟内的单据数量」
    private static final ConcurrentHashMap<String, ConcurrentHashMap<String, AtomicInteger>> orderTypeWithNo = new ConcurrentHashMap<>();
    private static final Set<String> ORDER_TYPE = new CopyOnWriteArraySet<>(new CopyOnWriteArraySet<>());

    public static String generateOrderNo(String orderType) {
        //检查是否已经存在此单据类型如果没有就加入
        if (!ORDER_TYPE.contains(orderType)) {
            ORDER_TYPE.add(orderType);
            orderTypeWithNo.put(orderType, new ConcurrentHashMap<>());
        }
        //获取此单据的No生成器
        ConcurrentHashMap<String, AtomicInteger> minuteCounters = orderTypeWithNo.get(orderType);
        //获取当前时间
        String currentMinute = OrderConstant.getCurrentTimeFormat();
        //清理过期的计数器
        cleanupOldCounters(minuteCounters, currentMinute);
        // 获取或创建当前分钟的计数器
        AtomicInteger counter = minuteCounters.computeIfAbsent(currentMinute, k -> new AtomicInteger(0));
        // 增加计数器并获取当前值
        int count = counter.incrementAndGet();

        // 生成订单编号
        return orderType + currentMinute + String.format("%01d", count);
    }

    private static void cleanupOldCounters(ConcurrentHashMap<String, AtomicInteger> minuteCounters, String currentMinute) {
        // 清理过期的分钟计数器
        minuteCounters.keySet().removeIf(key -> key.compareTo(currentMinute) < 0);
    }
}
